package hu.village.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
@Slf4j
public class MailUtil {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String userName;

    //发送邮箱验证的方法
    public Integer sendEmail(String receiver,String state){
        Random r = new Random();
        try{
            String subjectName = "验证";
            String condition = "";
            if (state.equals("0")){
                condition = "注册";
            }else if (state.equals("1")){
                condition = "登录";
            }
            String contentTemplate = "您正在执行"+condition+"操作,验证码是%s,两分钟内有效";
            Integer verifyCode = r.nextInt(100000,999999);

            String content = String.format(contentTemplate,verifyCode);

            //定义email信息格式
            SimpleMailMessage message = new SimpleMailMessage();
            //设置发件人
            message.setFrom(userName);
            //接收者邮箱
            message.setTo(receiver);
            //邮件主题
            message.setSubject(subjectName);
            message.setText(content);
            log.info("开始发送消息");
            mailSender.send(message);
            log.info("消息发送成功");
            return verifyCode;
        }catch (Exception e){
            log.error("send mail error", e);
            return null;
        }
    }
}
